package middleware

import (
	"github.com/gin-gonic/gin"
	e "shop/pkg/err"
)

func ExceptionMiddleware(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			switch v := err.(type) {
			case e.ApiError:
				c.JSON(500, gin.H{"code": v.Code, "msg": v.Msg})
				c.Abort()
			case error:
				c.JSON(500, gin.H{"code": "-1", "msg": v.Error()})
				c.Abort()
			default:
				c.JSON(500, gin.H{"code": "-1", "msg": err.(string)})
				c.Abort()
			}
		}
	}()
	c.Next()
}
